package org.zh.util.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;

public class ChatClient {
    private WebSocket webSocket;
    private String username;

    public ChatClient(String username) {
        this.username = username;
    }

    public static void main(String[] args) throws IOException {
        System.out.print("请输入用户名: ");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String username = reader.readLine();

        ChatClient client = new ChatClient(username);
        client.connect("ws://localhost:8080/chat");

        System.out.println("输入消息发送，输入 'exit' 退出");
        String line;
        while ((line = reader.readLine()) != null) {
            if ("exit".equalsIgnoreCase(line)) {
                break;
            }
            client.sendMessage(line);
        }

        client.close();
        reader.close();
    }

    public void connect(String serverUrl) {
        HttpClient client = HttpClient.newHttpClient();

        webSocket = client.newWebSocketBuilder()
                .buildAsync(URI.create(serverUrl), new WebSocket.Listener() {
                    @Override
                    public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
                        System.out.println(data);
                        return WebSocket.Listener.super.onText(webSocket, data, last);
                    }

                    @Override
                    public void onOpen(WebSocket webSocket) {
                        System.out.println("已连接到服务器");
                        webSocket.sendText(username + " 加入了聊天室", true);
                        WebSocket.Listener.super.onOpen(webSocket);
                    }

                    @Override
                    public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
                        System.out.println("连接已关闭: " + statusCode + ", " + reason);
                        return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
                    }

                    @Override
                    public void onError(WebSocket webSocket, Throwable error) {
                        System.out.println("发生错误: " + error.getMessage());
                    }
                })
                .join();
    }

    public void sendMessage(String message) {
        webSocket.sendText(username + ": " + message, true);
    }

    public void close() {
        webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "用户退出");
    }
}